package com.whpost.service.service.cwqf;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.cwqf.HsJgMapper;
import com.whpost.service.dao.cwqf.TCwqfKhzfFilesMapper;
import com.whpost.service.dao.cwqf.TCwqfKhzfMapper;
import com.whpost.service.dao.cwqf.TbCrmCustomerMapper;
import com.whpost.service.entity.cwqf.*;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TCwqfKhzfServices extends BaseServices<TCwqfKhzfMapper, TCwqfKhzf> {

    @Resource
    private FileService fileService;
    @Resource
    private TCwqfKhzfFilesMapper tCwqfKhzfFilesMapper;

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{

            String curpage = "",pagesize="",cxmc="",sfjm="1",ksrq="",jsrq="";
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("cxmc")) {
                cxmc = jsonObject.getString("cxmc");
            }
            if (jsonObject.containsKey("ksrq")) {
                ksrq = jsonObject.getString("ksrq");
            }
            if (jsonObject.containsKey("jsrq")) {
                jsrq = jsonObject.getString("jsrq");
            }
            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if (null==hsCzy){
                return new ResultInfo(500,"未获取用户信息！",null);
            }

            Page<TCwqfKhzf> page = new Page<>(Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<TCwqfKhzf> tCwqfKhzfListInfo = new ListInfo<>();
            QueryWrapper<TCwqfKhzf> tCwqfKhzfQueryWrapper = new QueryWrapper<TCwqfKhzf>();

            ksrq=ksrq+" 00:00:00";
            jsrq=jsrq+" 23:59:59";

            // 日期格式化器（匹配拼接后的字符串格式，必须与 ksrq/jsrq 格式一致）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startDate = null;
            Date endDate = null;

            try {
                // 字符串转 Date 类型（数据库 lrrq 是 Date 型，必须用 Date 类型对比）
                startDate = sdf.parse(ksrq);
                endDate = sdf.parse(jsrq);
            } catch (ParseException e) {
                // 异常处理：日期格式错误（例如前端传递的日期不是 yyyy-MM-dd 格式）
                return new ResultInfo(500, "日期格式错误，请检查开始/结束日期！！",null);
            }

            tCwqfKhzfQueryWrapper.eq("lrry",hsCzy.getCode());

            tCwqfKhzfQueryWrapper.ge("lrrq", startDate)
                    .le("lrrq", endDate);

            tCwqfKhzfQueryWrapper.orderByDesc("id");
            tCwqfKhzfQueryWrapper.eq("state","1");

            IPage<TCwqfKhzf> tQfkbBkIPage = getBaseMapper().getTCwqfKhzfPage(page,tCwqfKhzfQueryWrapper);
            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(tQfkbBkIPage.getTotal());
            pageInfo.setCurPage(tQfkbBkIPage.getCurrent());
            pageInfo.setPageSize(tQfkbBkIPage.getSize());
            pageInfo.setPageTotal(tQfkbBkIPage.getPages());

            tCwqfKhzfListInfo.setPageInfo(pageInfo);
            tCwqfKhzfListInfo.setListInfo(tQfkbBkIPage.getRecords());
            tCwqfKhzfListInfo.setUserId(loginId);//登录人员id，可以不设置也行

            //加密返回给前端
            if ("1".equals(sfjm)){
                ResultInfo resultInfo = new ResultInfo(200, "成功返回！",tCwqfKhzfListInfo);
                return backRtn(resultInfo,loginId);
            }else{
                //非加密,返回给其它方法使用
                return new ResultInfo(200, "成功返回！",tCwqfKhzfListInfo);
            }
        }
    }

    @Transactional
    public ResultInfo save(String loginId, List<MultipartFile> file, String data) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            JSONObject jsonObject = getDataStr(data,loginId);
            String lx="",id="",customerName="",customerCode="",phone="",remark="",is_app="",visitMode="";    //来源，如果是APP，则为1
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("customerName")) {
                customerName = jsonObject.getString("customerName");
            }
            if (jsonObject.containsKey("customerCode")) {
                customerCode = jsonObject.getString("customerCode");
            }
            if (jsonObject.containsKey("phone")) {
                phone = jsonObject.getString("phone");
            }
            if (jsonObject.containsKey("visitMode")) {
                visitMode = jsonObject.getString("visitMode");
            }
            if (jsonObject.containsKey("remark")) {
                remark = jsonObject.getString("remark");
            }
            if (jsonObject.containsKey("is_app")) {
                is_app = jsonObject.getString("is_app");
            }
            if (StringUtils.isEmpty(lx)){
                return new ResultInfo(500,"关键参数信息丢失！",null);
            }
            if (StringUtils.isEmpty(customerCode)){
                return new ResultInfo(500,"客户信息丢失！",null);
            }
            if (StringUtils.isEmpty(visitMode)){
                return new ResultInfo(500,"走访信息丢失！",null);
            }

            HsCzy hsCzy = getHsCzyMapper().selectByCode(loginId);

            if (null==hsCzy){
                return new ResultInfo(500,"用户信息丢失！",null);
            }


            TCwqfKhzf tCwqfKhzf = new TCwqfKhzf();

            if ("1".equals(lx)){
                tCwqfKhzf = getBaseMapper().selectById(id);
            }
            tCwqfKhzf.setKhCode(customerCode);
            tCwqfKhzf.setZffsId(Long.parseLong(visitMode));
            tCwqfKhzf.setLxdh(phone);
            tCwqfKhzf.setBz(remark);
            tCwqfKhzf.setLrjg(hsCzy.getSsjgLsh());
            tCwqfKhzf.setLrry(hsCzy.getCode());
            tCwqfKhzf.setLrrq(ToolBean.getToday());

            if ("1".equals(lx)){
                //修改的时候，文件上传变更
                getBaseMapper().updateById(tCwqfKhzf);
                return new ResultInfo(200,"修改成功！",null);
            }else{
                getBaseMapper().insert(tCwqfKhzf);
                //上传文件
                if (null!=file){
                    for (MultipartFile wj : file) {

                        if (StringUtils.isEmpty(wj.getOriginalFilename())){
                            continue;
                        }
                        ToolBean.info("wj:"+wj);
                        Long fileId= fileService.uploadFile(wj,loginId);

                        TCwqfKhzfFiles tCwqfKhzfFiles = new TCwqfKhzfFiles();
                        tCwqfKhzfFiles.setZfId(tCwqfKhzf.getId());
                        tCwqfKhzfFiles.setFileId(fileId);
                        tCwqfKhzfFilesMapper.insert(tCwqfKhzfFiles);

                    }
                }
                return new ResultInfo(200,"登记成功！",null);
            }
        }
    }


    /**
     * 走访看板
     * @param loginId
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo zfkb(String loginId,Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String ksrq="",jsrq="",jb="",jg_code="";
            if (jsonObject.containsKey("ksrq")) {
                ksrq = jsonObject.getString("ksrq");
            }
            if (jsonObject.containsKey("jsrq")) {
                jsrq = jsonObject.getString("jsrq");
            }
            if (jsonObject.containsKey("jb")) {
                jb = jsonObject.getString("jb");
            }
            if (jsonObject.containsKey("jg_code")) {
                jg_code = jsonObject.getString("jg_code");
            }

            if (StringUtils.isEmpty(ksrq) || StringUtils.isEmpty(jsrq)){
                return new ResultInfo(500,"日期参数丢失！",null);
            }

            if (StringUtils.isEmpty(jb)){
                return new ResultInfo(500,"机构统计层级丢失！",null);
            }

            if ("3".equals(jb) && StringUtils.isEmpty(jg_code)){
                return new ResultInfo(500,"上级机构信息丢失！",null);
            }

            ksrq=ksrq+" 00:00:00";
            jsrq=jsrq+" 23:59:59";

            // 返回结果
            Map<String, Object> rtnMap = new HashMap<>();

            // 预定义80个不重复的颜色代码
            String[] presetColors = {
                    // 原有20个颜色
                    "#FF5733", "#33FF57", "#3357FF", "#F3FF33", "#FF33F3",
                    "#33FFF3", "#F333FF", "#FF9933", "#99FF33", "#33FF99",
                    "#3399FF", "#9933FF", "#FF3399", "#993333", "#339933",
                    "#333399", "#999933", "#993399", "#339999", "#999999",
                    // 新增60个颜色
                    "#FF6B6B", "#4ECDC4", "#45B7D1", "#FFA07A", "#98D8C8",
                    "#F0E68C", "#DDA0DD", "#FF6347", "#20B2AA", "#87CEFA",
                    "#778899", "#B0C4DE", "#32CD32", "#F08080", "#FFD700",
                    "#6495ED", "#FFFACD", "#ADFF2F", "#FF69B4", "#CD5C5C",
                    "#4682B4", "#F4A460", "#9ACD32", "#FFC0CB", "#87CEEB",
                    "#66CDAA", "#00CED1", "#9370DB", "#8A2BE2", "#00FF7F",
                    "#FF4500", "#DA70D6", "#EEE8AA", "#98FB98", "#AFEEEE",
                    "#DB7093", "#FFE4B5", "#2E8B57", "#D2B48C", "#FFE4E1",
                    "#008080", "#DAA520", "#C71585", "#808080", "#0000CD",
                    "#008000", "#FF0000", "#0000FF", "#FFFF00", "#800080",
                    "#00FFFF", "#FF00FF", "#C0C0C0", "#800000", "#008080",
                    "#FFA500", "#808000", "#FFC0CB", "#A52A2A", "#7FFF00",
                    "#D2691E", "#FF7F50", "#6A5ACD", "#9400D3", "#FF8C00"
            };

            HsCzy hsCzy = getHsCzyMapper().selectById(loginId);

            String gljg = hsCzy.getGljg();
            ToolBean.info("gljg:" + gljg); // 输出：gljg:6,7,8,9,10

            List<Integer> ll = new ArrayList<>();

            // 处理逻辑：拆分字符串并转换为Integer
            if (gljg != null && !gljg.trim().isEmpty()) {
                // 按逗号拆分字符串为数组
                String[] gljgArray = gljg.split(",");
                for (String str : gljgArray) {
                    try {
                        // 去除空格并转换为Integer，添加到列表
                        ll.add(Integer.parseInt(str.trim()));
                    } catch (NumberFormatException e) {
                        // 处理非数字格式的异常（如字符串中包含字母等）
                        ToolBean.info("关联机构转换错误！");
                    }
                }
            }

            // 此时ll中就包含了6,7,8,9,10对应的Integer对象

            List<OrgCountDTO> orgCountDTOList;
            if ("3".equals(jb)){
                orgCountDTOList = getBaseMapper().statisticOrgDataByCode(jg_code, ksrq, jsrq);
            } else {
                orgCountDTOList = getBaseMapper().statisticOrgData(ksrq, jsrq,ll);
            }

            // 为每个OrgCountDTO按顺序填充颜色
            for (int i = 0; i < orgCountDTOList.size(); i++) {
                // 取模运算确保颜色循环使用
                int colorIndex = i % presetColors.length;
                orgCountDTOList.get(i).setYsdm(presetColors[colorIndex]);
            }

            rtnMap.put("orgCountDTOList", orgCountDTOList);


            ResultInfo resultInfo = new ResultInfo(200, "成功返回！", rtnMap);
            return backRtn(resultInfo, loginId);
        }
    }

    @Override
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else {
            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }

            if (StringUtils.isEmpty(id)){
                return new ResultInfo(500,"要删除的数据不存在！",null);
            }

            // 返回结果
            Map<String, Object> rtnMap = new HashMap<>();
            TCwqfKhzf tCwqfKhzf = getBaseMapper().selectById(id);
            if (tCwqfKhzf!=null){
                if (!tCwqfKhzf.getLrry().equals(loginId)){
                    ResultInfo resultInfo = new ResultInfo(500, "不能删除非自己维护的数据！", rtnMap);
                    return backRtn(resultInfo, loginId);
                }else{
                    getBaseMapper().deleteById(id);
                    ResultInfo resultInfo = new ResultInfo(200, "删除成功！", rtnMap);
                    return backRtn(resultInfo, loginId);
                }

            }else{
                ResultInfo resultInfo = new ResultInfo(500, "要删除的数据不存在！", rtnMap);
                return backRtn(resultInfo, loginId);
            }
        }
    }

}